package com.sihai.ehr.web.action.exam;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.*;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.ExaminePeriodEnum;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.*;
import com.sihai.ehr.utils.PeriodUtils;
import com.sihai.ehr.web.action.EHRAction;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author wxn
 * @since 12-10-22 21:58
 * 定量考核数据输入Action
 */
@Results({
        @Result(name = "main", location = "exam_quan_input_main.jsp"),
        @Result(name = "list_uninput", location = "exam_quan_input_list_uninput.jsp"),
        @Result(name = "list_input", location = "exam_quan_input_list_input.jsp"),
        @Result(name = "add", location = "exam_quan_input_add.jsp")
})
public class ExamQuanInputAction extends EHRAction {
    @BeanInject
    private DutyService dutyService;
    @BeanInject
    private OrganizationService organizationService;
    @BeanInject
    private ExamBaseConfigService examBaseConfigService;
    @BeanInject
    private ExamQuanDataInputService examQuanDataInputService;
    @BeanInject
    private EmployeeService employeeService;
    @BeanInject
    private ExamPeriodService examPeriodService;

    private List<Organization> organizations;

    private LimitedList<EmployeeinfoWork> employeeinfoWorks;

    private String examPeriodStr; //2012年5月, 2012年1~3月
    private ExaminePeriodEnum examPeriodEnum;//月，双朋，季，半年，年

    private EmployeeinfoWork work;
    private List<ExamQuanItemSet> examQuanItemSets;
    private LimitedList<ExamQuanScoreDetail> examQuanScoreDetails;
    private boolean isEdit;
    private AuditStatus status;

    private int dataTotal;

    private boolean hasSubmit;
    private Float prevScore;

    //量化数据输入主界面
    @Action("/exam/quan_input_main")
    @Override
    public String execute() throws Exception {
        listAction = "/exam/quan_input_main.xhtml";
        listTitle = "量化数据输入";
        showChildOrg = true;
        organizations = organizationService.findChildren(null, true, null, null);
        if (organizations != null && organizations.size() > 0) {
        	if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
            organizationId = organizations.get(0).getId();
        }
        return "main";
    }

    //跳转到数据输入页面
    @Action("/exam/quan_data_input_add")
    public String add() throws Exception {
        User user = getCurrentUser();
        if(user == null || user.getId() == null || user.getId() <= 0){
            return execute();
        }

        if(work == null || work.getId() == null || work.getId() <= 0){
            return execute();
        }
        work = employeeService.getEmployeeinfoWork(work.getId());
        if(!isEdit ){//创建(读定量考核项目表)
            examQuanItemSets = examQuanDataInputService.findExamQuanItemSetForInput(user, work.getDuty().getId(), examPeriodEnum, null, null);
            isEdit = false;
        }else{//修改(读打分详细表)
            ExamEmbedPeriod period = PeriodUtils.createEmbedPeriod(examPeriodStr, examPeriodEnum);
            if(period == null){
                return execute();
            }
            if(status == AuditStatus.wait_audit){
                if(NumberUtils.createInteger(getParameter("reject_time")) > 0){
                    status = AuditStatus.reject_audit;
                }
                isEdit = true;
            }else{
            }
            examQuanScoreDetails = examQuanDataInputService.searchExamQuanDetails("input", user, organizationId, work.getId(), period, status, null, null);

        }
        return "add";
    }
    //数据输入(添加或修改打分)
    @Action("/exam/quan_data_input_create")
    public String create() throws Exception {
        if(work == null || work.getId() == null || work.getId() <= 0){
            return execute();
        }

        work = employeeService.getEmployeeinfoWork(work.getId());

        String[] itemIds = getParameterValues("item_id"); //修改时保存的是ExamQuanScoreDetail的id列表，　添加时保存的是ExamQuanItemSet的id列表
        String[] numerals = getParameterValues("numeral");
        String[] scores = getParameterValues("score");
        if(itemIds == null || numerals == null || scores == null || itemIds.length != numerals.length || itemIds.length != scores.length){
            return execute();
        }

        ExamEmbedPeriod period = PeriodUtils.createEmbedPeriod(examPeriodStr, examPeriodEnum);
        if(period == null){
            return execute();
        }

        //得到本职务的考核配置对象
        ExamBaseConfig baseConfig = examBaseConfigService.getExamBaseConfigByDutyId(work.getDuty().getId());
        if(baseConfig == null){
            return execute();
        }
        ExaminePeriodEnum configPeriod = baseConfig.getPeriodType(); //得到配置于职务的大周期
        if(configPeriod == null){
            return execute();
        }

        ExamPeriod p = PeriodUtils.createPeriod(period, configPeriod);//得到小周期所属的大周期
        //查周期，没有就创建一个
        Long pid = examPeriodService.getExamPeriodByTypeAndYMonthly(p.getPeriodType(), p.getExamYear(), p.getExamMonthly());
        if(pid != null && pid > 0){
            p.setId(pid);
        }else{
            examPeriodService.saveExamPeriod(p);
        }

        int size = itemIds.length;
        List<ExamQuanScoreDetail> scoreDetails = new ArrayList<ExamQuanScoreDetail>(size);

        for(int i=0; i<size; i++){
            Long id = NumberUtils.createLong(itemIds[i]);
            ExamQuanScoreDetail detail = null;
            if(isEdit()){//修改打分
                detail = examQuanDataInputService.getExamQuanScoreDetail(id);
                if(detail == null){
                    continue;
                }
            }else{//添加打分
                ExamQuanItemSet item = examQuanDataInputService.getExamQuanItemSet(id);
                if(item == null){
                    continue;
                }
                detail = new ExamQuanScoreDetail();
                detail.setExamQuanItemSet(item);
                detail.setEmbedPeriod(period);//设置小周期
                detail.setEmployeeinfoWork(work);
                detail.setExamPeriod(p);//设置大周期
                detail.setStatus(AuditStatus.wait_submit); //2012.12.17:未提交输入前，状态为待提交
            }
            detail.setNumeral(NumberUtils.createFloat(numerals[i]));
            detail.setScore(NumberUtils.createFloat(scores[i]));

            scoreDetails.add(detail);
        }
        examQuanDataInputService.saveDateInputs(scoreDetails);

        return execute();
    }

    //检查是否可提交输入
    @Action(value = "/ajax/quan_submit_check", results = { @Result(name = "success", type = "json", params = {"root", "hasSubmit" }) })
    public String checkCanSubmitInput() throws Exception {
        ExamEmbedPeriod period = PeriodUtils.createEmbedPeriod(examPeriodStr, examPeriodEnum);
        if(period == null){
            return null;
        }
        hasSubmit = examQuanDataInputService.submitCheck(period, getCurrentUser());
        return SUCCESS;
    }
    //提交输入
    @Action(value = "/ajax/quan_submit_input", results = { @Result(name = "success", type = "json", params = {"root", "hasSubmit" }) })
    public String submitInput() throws Exception {
        ExamEmbedPeriod period = PeriodUtils.createEmbedPeriod(examPeriodStr, examPeriodEnum);
        if(period == null){
            return SUCCESS;
        }
        try {
            hasSubmit = examQuanDataInputService.submitInput(period, getCurrentUser());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    //读上次考核记录分数
    @Action(value = "/ajax/exam_prev_score", results = { @Result(name = "success", type = "json", params = {"root", "prevScore" }) })
    public String prevScore() throws Exception {
        if(work == null || work.getId() == null || examPeriodEnum == null){
            return null;
        }
        prevScore = examQuanDataInputService.prevScore(work.getId(), examPeriodEnum);
        return SUCCESS;
    }

    //定量考核数据输入－未输入列表
    @Action("/exam/quan_uninput_list")
    public String listUnInput() throws Exception {
        ExamEmbedPeriod period = PeriodUtils.createEmbedPeriod(examPeriodStr, examPeriodEnum);
        if(period == null){
            return "list_uninput";
        }
        User user = getCurrentUser();
        if(user == null || user.getId() == null || user.getId() <= 0){
            return "list_uninput";
        }

        boolean findForAll = BooleanUtils.toBoolean(getParameter("findForAll"));
        if(organizationId != null && organizationId <= 0){
            organizationId = null;
        }
        //employeeinfoWorks = examQuanDataInputService.searchExamQuanUnInputs(organizationId, period, createLimit(), createSorter());
        employeeinfoWorks = examQuanDataInputService.searchExamQuanUnInputsByItems(user, organizationId, period, createLimit(), createSorter());
        if(employeeinfoWorks != null){
            dataTotal = employeeinfoWorks.getTotalcount();
        }

        /* 分页 */
        this.paging(employeeinfoWorks);
        /* 设置翻页action */
        this.setPageUrl("exam/quan_uninput_list.xhtml");

        return "list_uninput";
    }

    //定量考核数据输入－已输入列表
    @Action("/exam/quan_input_list")
    public String listInput() throws Exception {
        User user = getCurrentUser();
        if(user == null || user.getId() == null || user.getId() <= 0){
            return "list_input";
        }

        ExamEmbedPeriod period = PeriodUtils.createEmbedPeriod(examPeriodStr, examPeriodEnum);
        if(period == null){
            return "list_input";
        }

        /*boolean hasSubmit = examQuanDataInputService.submitCheck(period, getCurrentUser());
        //如果没有提交，则查找状态为null的列表
        if(!hasSubmit){
            status = AuditStatus.wait_submit;
        }*/

        if(organizationId != null && organizationId <= 0){
            organizationId = null;
        }
        //setCount(3);
        examQuanScoreDetails = examQuanDataInputService.searchExamQuanDetails("input", user, organizationId, null, period, status, createLimit(), createSorter());
        if(examQuanScoreDetails != null){
            dataTotal = examQuanScoreDetails.getTotalcount();
        }

        /* 分页 */
        this.paging(examQuanScoreDetails);
        /* 设置翻页action */
        this.setPageUrl("exam/quan_input_list.xhtml");

        return "list_input";
    }

    public List<Organization> getOrganizations() {
        return organizations;
    }

    public LimitedList<EmployeeinfoWork> getEmployeeinfoWorks() {
        return employeeinfoWorks;
    }

    public String getExamPeriodStr() {
        return examPeriodStr;
    }

    public void setExamPeriodStr(String examPeriodStr) {
        this.examPeriodStr = examPeriodStr;
    }

    public ExaminePeriodEnum getExamPeriodEnum() {
        return examPeriodEnum;
    }

    public void setExamPeriodEnum(ExaminePeriodEnum examPeriodEnum) {
        this.examPeriodEnum = examPeriodEnum;
    }

    public EmployeeinfoWork getWork() {
        return work;
    }

    public void setWork(EmployeeinfoWork work) {
        this.work = work;
    }

    public List<ExamQuanItemSet> getExamQuanItemSets() {
        return examQuanItemSets;
    }

    public LimitedList<ExamQuanScoreDetail> getExamQuanScoreDetails() {
        return examQuanScoreDetails;
    }

    public boolean isEdit() {
        return isEdit;
    }

    public void setEdit(boolean edit) {
        isEdit = edit;
    }

    public int getDataTotal() {
        return dataTotal;
    }

    public AuditStatus getStatus() {
        return status;
    }

    public void setStatus(AuditStatus status) {
        this.status = status;
    }

    public boolean isHasSubmit() {
        return hasSubmit;
    }

    public Float getPrevScore() {
        return prevScore;
    }
}
